//========================================================= 
/**@file  NesMapper_2.h
 * @brief  
 * 
 * @date 2024-07-19 16:17:36 
 * @author yingbaizhou@tencent.com 
 * @version 1.0
 */ 
//--------------------------------------------------------- 
#ifndef _LIBZHOUYB_NESMAPPER_2_H_
#define _LIBZHOUYB_NESMAPPER_2_H_
//--------------------------------------------------------- 
#include "../INesInterface.h"
#include "../NesMapper.h"
//--------------------------------------------------------- 
namespace zhou_yb {
namespace wrapper {
namespace nes {
//--------------------------------------------------------- 
class NesMapper_2 : public INesMapper, public IPrgMapperRouter, public RefObject
{
public:
    static const int PRG_BANK_SIZE = 16 * 1024;
protected:
    RawMapper _chr;
    PrgRouterAdapter _prg;

    ByteArray _prg_buff;
    uint _last_bank_address = 0;
    uint _switchable_bank_address = 0;
public:
    virtual bool Set(const NesROM& rom)
    {
        _chr.Set(rom.chr);
        _prg.Set(*this);

        _prg_buff = rom.prg;
        _switchable_bank_address = 0;
        _last_bank_address = (rom.prg_count - 1) << 14;
        return true;
    }
    virtual IMapper* GetChrMapper() { return &_chr; }
    virtual IMapper* GetPrgMapper() { return &_prg; }

    virtual byte PrgRead(ushort addr)
    {
        uint bank_addr = 0;
        if (addr <= 0x3FFF)
            bank_addr = _switchable_bank_address + addr;
        else
            bank_addr = _last_bank_address + (addr & 0x3FFF);
        return _prg_buff[bank_addr];
    }
    virtual void PrgWrite(ushort addr, byte value)
    {
        uint bank_address = (value & 0x0F) << 14;
        _switchable_bank_address = bank_address;
    }

    virtual void Reset()
    {
        _switchable_bank_address = 0;
    }
};
//--------------------------------------------------------- 
} // namespace nes
} // namespace wrapper
} // namespace zhou_yb
//---------------------------------------------------------
#endif // _LIBZHOUYB_NESMAPPER_2_H_
//=========================================================